import Window_ChangeLangConfirm from "./confirm";
//-----------------------------------------------------------------------------
// Window_Options
//
// The window for changing various settings on the options screen.

Window_Options.prototype = Object.create(Window_Command.prototype);
Window_Options.prototype.constructor = Window_Options;

Window_Options.prototype.initialize = function () {
  Window_Command.prototype.initialize.call(this, 0, 0);
  this.updatePlacement();
  this._backgroundSprite = new Sprite();
  this._backgroundSprite.bitmap = ImageManager.loadBitmap(
    "img/system/UI/",
    "MenuBg_OptionsList"
  );
  this.addChildAt(this._backgroundSprite, 0);
  this._backgroundSprite.x = -17;
  this._backgroundSprite.y = -1;
  this.opacity = 0;
};

Window_Options.prototype.windowWidth = function () {
  return 384;
};

Window_Options.prototype.windowHeight = function () {
  return this.fittingHeight(Math.min(this.numVisibleRows(), 12));
};

Window_Options.prototype.numVisibleRows = function () {
  return 8;
};

Window_Options.prototype.updatePlacement = function () {
  this.x = (Graphics.boxWidth - this.width) / 2;
  this.y = (Graphics.boxHeight - this.height) / 2;
};

// SWDA：更改顺序
Window_Options.prototype.makeCommandList = function () {
  this.addGeneralOptions();
};


// SWDA：新增记录/读取/记载选项
Window_Options.prototype.addGeneralOptions = function () {
  if (!SceneManager.isTitleOptions()) {
    this.addCommand(TextManager.save, "save", this.isSaveEnabled());
    this.addCommand("读    取", "load");
  }
  this.addCommand(TextManager.bgmVolume, "bgmVolume");
  this.addCommand(TextManager.seVolume, "seVolume");
  this.addCommand("信息速度", "messageSpeed");
  //this.addCommand('游戏速度', 'gameSpeed');           //未完成
  this.addCommand(TextManager.alwaysDash, "alwaysDash");
  this.addCommand(TextManager.commandRemember, "commandRemember");
  //effect
  this.addCommand("角色阴影", "characterShaddow");
  this.addCommand("场景动态", "animatedMap");
  this.addCommand("战斗运镜", "battleCamera");
  this.addCommand("敌人动态", "animatedEnemy");
  //其它
  this.addCommand("伤害样式", "damageStyle");
  this.addCommand("护驾顺序", "enemySort");
  this.addCommand("语    言", "language");

  if (Utils.isNwjs() && !Utils.isMobileDevice()) {
    this.addCommand("全屏显示", 'fullscreen');
  }

  //if (Utils.isMobileDevice()) {
    this.addCommand("虚拟按键设置", 'virtualButton');
  //}
  if (!Utils.isMobileDevice()) {
    this.addCommand("键盘设置", "keyConfig");
    this.addCommand("控制器设置", "gamepadConfig", Input.isControllerConnected());
    
  }
  
  this.addCommand("控制器震动", "rumbleOption", Input.isControllerConnected() || Utils.isMobileDevice());
  
  if (!SceneManager.isTitleOptions()) {
    this.addCommand("帮    助", "manual");
    this.addCommand(TextManager.gameEnd, "gameEnd");
  }
};

// BGM和ME合并；BGS和SE合并
Window_Options.prototype.drawItem = function (index) {
  var rect = this.itemRectForText(index);
  var statusWidth = this.statusWidth();
  var titleWidth = rect.width - statusWidth;
  this.resetTextColor();
  this.changePaintOpacity(this.isCommandEnabled(index));
  this.drawText(this.commandName(index), rect.x, rect.y, titleWidth, "left");

  var symbol = this.commandSymbol(index);
  var value = this.getConfigValue(symbol);
  if (this.isVolumeSymbol(symbol)) {
    var rate = value / 100;
    this.drawOptionsGauge(index, rate);
  } else if (this.isSpeedSymbol(symbol)) {
    var rate = value / 4;
    this.drawOptionsGauge(index, rate);
  }
  this.setSmallerFont();
  this.contents.fontSize = 20;
  this.changeTextColor(this.textColor(23));
  this.drawText(
    this.statusText(index),
    titleWidth,
    rect.y,
    statusWidth,
    "right"
  );
  this.resetFontSettings();
};

Window_Options.prototype.statusWidth = function () {
  return 120;
};

// 补充其它类型的条目（非音量符合或）——文字
Window_Options.prototype.statusText = function (index) {
  var symbol = this.commandSymbol(index);
  var value = this.getConfigValue(symbol);

  if (this.isVolumeSymbol(symbol)) {
    return this.volumeStatusText(value);
  }

  if (this.isSpeedSymbol(symbol)) {
    return this.speedText(value);
  }
  if (symbol == "damageStyle" ){
    return this.booleanDamageStyleText(value);
  }
  if (symbol == "enemySort" ){
    return this.booleanEnemySortText(value);
  }
  if (
    symbol == "alwaysDash" ||
    symbol == "commandRemember" ||
    this.isEffectSymbol(symbol) ||
    symbol == "rumbleOption"
  ) {
    return this.booleanStatusText(value);
  }

  if (symbol == "language") {
    return this.booleanLanguageText(value);
  }

  if (symbol == "fullscreen") {
    return this.booleanStatusText(value)
  }

  return ""
};

Window_Options.prototype.speedText = function (i) {
  const speedText = ["最慢", "较慢", "中速", "较快", "最快"];
  return speedText[i];
};

Window_Options.prototype.isVolumeSymbol = function (symbol) {
  return symbol.contains("Volume");
};

Window_Options.prototype.isSpeedSymbol = function (symbol) {
  return symbol.contains("Speed");
};

Window_Options.prototype.isEffectSymbol = function (symbol) {
  return (
    symbol == "characterShaddow" ||
    symbol == "animatedMap" ||
    symbol == "animatedEnemy" ||
    symbol == "battleCamera"
  );
};

//更改文字
Window_Options.prototype.booleanStatusText = function (value) {
  return value ? "开" : "关";
};

//更改文字
Window_Options.prototype.booleanDamageStyleText = function (value) {
  return value ? "阿拉伯数字" : "中文数字";
};
//更改文字
Window_Options.prototype.booleanEnemySortText = function (value) {
  return value ? "等级优先" : "种族优先";
};

//更改文字
Window_Options.prototype.booleanLanguageText = function (value) {
  return value ? "繁體中文" : "简体中文";
};

Window_Options.prototype.volumeStatusText = function (value) {
  return value + "%";
};

// 补充其它类型的条目（非音量符合或）功能
Window_Options.prototype.processOk = function () {
  var index = this.index();
  var symbol = this.commandSymbol(index);
  var value = this.getConfigValue(symbol);
  if (symbol === "keyConfig") {
    Window_Command.prototype.processOk.call(this);
  } else if (symbol === "gamepadConfig") {
    Window_Command.prototype.processOk.call(this);
  } else if (this.isVolumeSymbol(symbol)) {
    value += this.volumeOffset();
    if (value > 100) value = 0;
    value = value.clamp(0, 100);
    this.changeValue(symbol, value);
  } else if (this.isSpeedSymbol(symbol)) {
    var value = this.getConfigValue(symbol);
    value += 1;
    if (value > 4) value = 0;
    value = value.clamp(0, 4);
    this.changeValue(symbol, value);
  } else if (symbol == "language") {
    this.callHandler("onConfirmShow");
  } else if (
    symbol == "alwaysDash" ||
    symbol == "commandRemember" ||
    this.isEffectSymbol(symbol) ||
    symbol == "damageStyle" ||
    symbol == "enemySort" ||
    (symbol == "rumbleOption" && Input.isControllerConnected())
  ) {
    this.changeValue(symbol, !value);
  } else if (symbol === "fullscreen") {
    this.changeValue(symbol, !value)
    this.applyFullscreenStatus(!value)
  } else {
    Window_Command.prototype.processOk.call(this);
  }
};

Window_Options.prototype.applyFullscreenStatus = function (value) {
  if (Utils.isNwjs()) {
    const nw = require("nw.gui")
    const screens = nw.Screen.screens
    const win = nw.Window.get()
    if (value) {
      win.enterFullscreen()
    } else {
      win.leaveFullscreen()
      const activeScreen = nw.Screen.screens.find((screen) => {
        const screenBounds = screen.bounds;
        // 判断窗口边界是否与屏幕边界完全匹配
        if (
          win.x === screenBounds.x &&
          win.y === screenBounds.y &&
          win.width === screenBounds.width &&
          win.height === screenBounds.height
        ) {
          return true
        }
      }) || nw.Screen.screens[0] // 找到窗口所在的屏幕，如果当前窗口跨屏幕则得到占据较多的一个窗口

      win.on('leave-fullscreen', function () {
        const workArea = activeScreen.work_area;
        const screenWidth = workArea.width;
        const screenHeight = workArea.height;

        // 获取窗口的宽度和高度
        const windowWidth = win.width;
        const windowHeight = win.height;

        // 计算窗口居中时的坐标
        const x = (screenWidth - windowWidth) / 2;
        const y = (screenHeight - windowHeight) / 2;

        // 设置居中，设置窗口大小（如果屏幕比1280x720小则使用屏幕大小，否则使用1280x720）
        win.x = x
        win.y = y
        win.width = Math.min(screenWidth, 1280)
        win.height = Math.min(screenHeight, 720)
      })
    }
  }
}

let _Window_Options_processTouch = Window_Options.prototype.processTouch;
Window_Options.prototype.processTouch = function () {
  var index = this.index();
  var symbol = this.commandSymbol(index);
  var value = this.getConfigValue(symbol);

  _Window_Options_processTouch.call(this);

  if (TouchInput.isTriggered() && this.isTouchedInsideFrame()) {
    const rect = this.statusRect(index);
    const valueX = this.canvasToLocalX(TouchInput.x) - this.padding - rect.x;
    const valueTotal = rect.width;
    if (this.isVolumeSymbol(symbol)) {
      value = (Math.round((valueX / valueTotal) * 10) * 10).clamp(0, 100);
      this.changeValue(symbol, value);
    } else if (this.isSpeedSymbol(symbol)) {
      value = Math.round((valueX / valueTotal) * 4).clamp(0, 4);
      this.changeValue(symbol, value);
    }
  }
};

Window_Options.prototype.cursorRight = function (wrap) {
  var index = this.index();
  var symbol = this.commandSymbol(index);
  var value = this.getConfigValue(symbol);
  if (this.isVolumeSymbol(symbol)) {
    value += this.volumeOffset();
    value = value.clamp(0, 100);
    this.changeValue(symbol, value);
  } else if (this.isSpeedSymbol(symbol)) {
    var value = this.getConfigValue(symbol);
    value += 1;
    value = value.clamp(0, 4);
    this.changeValue(symbol, value);
  } else if (symbol == "language") {
    this.callHandler("onConfirmShow");
  } else if (
    symbol == "alwaysDash" ||
    symbol == "commandRemember" ||
    this.isEffectSymbol(symbol) ||
    symbol == "damageStyle" ||
    symbol == "enemySort" ||
    (symbol == "rumbleOption" && Input.isControllerConnected())
  ) {
    this.changeValue(symbol, true);
  } else if (symbol === "fullscreen") {
    this.changeValue(symbol, !value)
    this.applyFullscreenStatus(!value)
  }
};

Window_Options.prototype.cursorLeft = function (wrap) {
  var index = this.index();
  var symbol = this.commandSymbol(index);
  var value = this.getConfigValue(symbol);
  if (this.isVolumeSymbol(symbol)) {
    value -= this.volumeOffset();
    value = value.clamp(0, 100);
    this.changeValue(symbol, value);
  } else if (this.isSpeedSymbol(symbol)) {
    var value = this.getConfigValue(symbol);
    value -= 1;
    value = value.clamp(0, 4);
    this.changeValue(symbol, value);
  } else if (symbol == "language") {
    this.callHandler("onConfirmShow");
  } else if (
    symbol == "alwaysDash" ||
    symbol == "commandRemember" ||
    this.isEffectSymbol(symbol) ||
    symbol == "damageStyle" ||
    symbol == "enemySort" ||
    (symbol == "rumbleOption" && Input.isControllerConnected())
  ) {
    this.changeValue(symbol, false);
  } else if (symbol === "fullscreen") {
    this.changeValue(symbol, !value)
    this.applyFullscreenStatus(!value)
  }
};

Window_Options.prototype.volumeOffset = function () {
  return 10;
};

Window_Options.prototype.changeValue = function (symbol, value) {
  const lastValue = this.getConfigValue(symbol);
  if (lastValue !== value) {
    this.setConfigValue(symbol, value);
    this.redrawItem(this.findSymbol(symbol));
    SoundManager.playCursor();
  }
};

Window_Options.prototype.getConfigValue = function (symbol) {
  return ConfigManager[symbol];
};

Window_Options.prototype.setConfigValue = function (symbol, volume) {
  if (symbol == "bgmVolume") ConfigManager["meVolume"] = volume;
  if (symbol == "seVolume") ConfigManager["bgsVolume"] = volume;
  ConfigManager[symbol] = volume;
};

Window_Options.prototype.drawOptionsGauge = function (index, rate) {
  var rect = this.statusRect(index);
  var c1 = this.textColor(14);
  var c2 = this.textColor(6);
  this.drawGauge(rect.x, rect.y - 6, rect.width, rate, c1, c2);
};

Window_Options.prototype.statusRect = function (index) {
  var rect = this.itemRectForText(index);
  var statusWidth = this.statusWidth();
  rect.x = rect.width - statusWidth - 56;
  rect.width = statusWidth;
  return rect;
};

Window_Options.prototype.isSaveEnabled = function () {
  return !DataManager.isEventTest() && $gameSystem.isSaveEnabled();
};

// ===========================================================================================================
// Scene_Options

Scene_Options.prototype.create = function () {
  Scene_MenuBase.prototype.create.call(this);
  this.createOptionsWindow();
  this.createGameEndWindow();
  this.createConfirmInfoWindow(); // 信息提示
  this.createConfirmWindow(); // 是否
};

Scene_Options.prototype.createOptionsWindow = function () {
  this._optionsWindow = new Window_Options();
  this._optionsWindow.setHandler("cancel", this.popScene.bind(this));
  if (!SceneManager.isTitleOptions())
    this._optionsWindow.setHandler("save", this.commandSave.bind(this));
  if (!SceneManager.isTitleOptions())
    this._optionsWindow.setHandler("load", this.commandLoad.bind(this));
  if (!SceneManager.isTitleOptions())
    this._optionsWindow.setHandler("manual", this.commandManual.bind(this));
  this._optionsWindow.setHandler("gameEnd", this.commandGameEnd.bind(this));
  this._optionsWindow.setHandler("keyConfig", this.commandKeyConfig.bind(this));
  this._optionsWindow.setHandler('virtualButton', this.commandVirtualButtonConfig.bind(this));
  this._optionsWindow.setHandler(
    "gamepadConfig",
    this.commandGamepadConfig.bind(this)
  );
  this._optionsWindow.setHandler(
    "onConfirmShow",
    this.commandConfirmShow.bind(this)
  );
  this._optionsWindow.setHandler(
    "onConfirmHide",
    this.commandConfirmHide.bind(this)
  );
  this.addWindow(this._optionsWindow);
};

Scene_Options.prototype.createGameEndWindow = function () {
  this._gameEndWindow = new Window_GameEnd();
  this._gameEndWindow.setHandler("toTitle", this.commandToTitle.bind(this));
  this._gameEndWindow.setHandler(
    "cancel",
    this.commandGameEndCancel.bind(this)
  );
  this._gameEndWindow.hide();
  this._gameEndWindow.deactivate();
  this.addWindow(this._gameEndWindow);
};

Scene_Options.prototype.createConfirmInfoWindow = function () {
  this._confirmInfoWindow = new Window_Help();
  this._confirmInfoWindow.x = 0;
  this._confirmInfoWindow.y = 550;
  this._confirmInfoWindow.hide();
  this._confirmInfoWindow.opacity = 0;
  this.addWindow(this._confirmInfoWindow);
};

Scene_Options.prototype.createConfirmWindow = function () {
  this._changeLangWindow = new Window_ChangeLangConfirm();
  this._changeLangWindow.x = 0;
  this._changeLangWindow.y = 0;
  this._changeLangWindow.setHandler(
    "ok",
    this.commandConfirmClickOk.bind(this)
  );
  this._changeLangWindow.setHandler(
    "cancel",
    this.commandConfirmClickCancel.bind(this)
  );
  this._changeLangWindow.hide();
  this._changeLangWindow.deactivate();
  this.addWindow(this._changeLangWindow);
};

Scene_Options.prototype.commandSave = function () {
  SceneManager.push(Scene_Save);
};

Scene_Options.prototype.commandLoad = function () {
  this._optionsWindow.close();
  SceneManager.push(Scene_Load);
};

Scene_Options.prototype.commandManual = function () {
  this._optionsWindow.close();
  SceneManager.openGameManual();
};

Scene_Options.prototype.commandGameEnd = function () {
  this._optionsWindow.deactivate();
  this._gameEndWindow.show();
  this._gameEndWindow.activate();
  //SceneManager.push(Scene_GameEnd);
};

Scene_Options.prototype.commandKeyConfig = function () {
  SceneManager.push(Scene_KeyConfig);
};

Scene_Options.prototype.commandVirtualButtonConfig = function () {
  SceneManager.push(Scene_VBOptions);
  //SceneManager.push(Scene_DebugVB);
};

Scene_Options.prototype.commandGamepadConfig = function () {
  SceneManager.push(Scene_GamepadConfig);
};


Scene_Options.prototype.commandToTitle = function () {
  this.fadeOutAll();
  SceneManager.goto(Scene_Title);
};

Scene_Options.prototype.commandGameEndCancel = function () {
  this._optionsWindow.activate();
  this._gameEndWindow.hide();
  this._gameEndWindow.deactivate();
};

// 展示切换语言用的确认框
Scene_Options.prototype.commandConfirmShow = function () {
  this._optionsWindow.deactivate();

  this._confirmInfoWindow.show();
  this._confirmInfoWindow.changeTextColor(this._confirmInfoWindow.textColor(0));
  const text = "语言切换后将强制重启游戏，确定要现在切换语言吗？";
  const textWidth = this._confirmInfoWindow.textWidth(text);
  this._confirmInfoWindow.drawText(text, 0, 0, textWidth);
  this._confirmInfoWindow.resetTextColor();

  setTimeout(() => {
    this._changeLangWindow.activate();
    this._changeLangWindow.show();
  }, 10);
};

// 隐藏切换语言用的确认框
Scene_Options.prototype.commandConfirmHide = function () {
  this._confirmInfoWindow.changeTextColor(this._confirmInfoWindow.textColor(0));
  const text = "语言切换后将强制重启游戏，确定切换语言吗？";
  const textWidth = this._confirmInfoWindow.textWidth(text);
  this._confirmInfoWindow.drawText(text, 0, 350, textWidth);
  this._confirmInfoWindow.resetTextColor();

  this._changeLangWindow.deactivate();
  this._confirmInfoWindow.deactivate();
  this._changeLangWindow.hide();
  this._confirmInfoWindow.hide();
  this._optionsWindow.activate();
};

// 按下确认切换语言的按钮
Scene_Options.prototype.commandConfirmClickOk = function () {
  const value = this._optionsWindow.getConfigValue("language");
  const nextValue = !value;

  this._changeLangWindow.hide();
  this._optionsWindow.activate();

  $gameGlobalManager.setLang(nextValue ? "zh-hant" : "zh-cn");
  this._optionsWindow.changeValue("language", nextValue);
  ConfigManager.save();
  window.location.reload();
};

// 取消按下切换语言的按钮
Scene_Options.prototype.commandConfirmClickCancel = function () {
  this._changeLangWindow.hide();
  this._confirmInfoWindow.hide();
  this._confirmInfoWindow.deactivate();
  this._changeLangWindow.deactivate();
  this._optionsWindow.activate();
};
